<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html style="height: 100%" lang="en">
	<base href="<%=basePath%>">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

	<title>赣通卡圈存</title>
	<link rel="stylesheet" href="css/base.css">
	<script src="js/jquery.min.js"></script>
	<script src="js/jweixin-1.0.0.js"></script>
	<script src="js/base.js"></script>
	<script src="js/common.js"></script>
	<script type="text/javascript" src="js/sha256.js"></script>
	<script type="text/javascript" src="js/sig.js"></script>
	<script src="js/handle.js"></script>
	<script src="js/jquery.bluetooth.js?v=201709261435"></script>

</head>
<body class="">
	<div class="toast toast_timeout" style="display:none">网络异常，请稍后重试！</div>
	<div class="toast toast_error" style="display:none"></div>
	<div class="loading" style="display:none">
		<img src="img/loading.gif"></div>
	<div class="wrap">
		<div class="rech_topbox">
			<div id="info"></div>
			<p>
				车牌
				<span class="float_btn" onclick="changeCard()"> <i></i>
					更换
				</span>
			</p>
			<h1>
				<span class='rech_balance' id="transferVpl"></span>
			</h1>
			<p>赣通卡号</p>
			<h2 id="transferCardNo"></h2>

		</div>
		<div class="rech_bodybox">
			<h3>圈存金额</h3>
			<div class="rech_body_input"> <i>¥</i>
				<input type="tel" maxlength="5" id="transfer_money">
				<div class="input_holder">
					<p>请输入圈存金额</p>
					<p>（100元整数倍）</p>
				</div>

			</div>
		</div>
		<div class="debit_btn disable" id="debit_btn">
			使用余额
			<span id="transferMoneyBtn"></span>
			支付
		</div>
		<p class="goToRecharge">
			余额不足? 更换微信支付
			<i></i>
		</p>
	</div>
	<div class="mask_layer none"></div>
	<script type="text/javascript">
		// checkHasDevide(); // 检查用户是否连接过设备
		var ble;
		var cardNoSelect = "${cardNo}";
		var balanceSelect = "${acctBalance}";
		var vehiclePlateSelect  = "${vehiclePlate}";
		var token = "${token}";
		var payMoney = ("${payMoney}").replace(/\D+/ig,""); //充值金额
		var result = eval( '(' + '${result}' + ')' ); // 储存卡列表接口原始数据
		// var result = eval( '(' + '{"obj":[{"acctBalance":"0","cardNo":"1422220000000453","cardType":"1","certificateid":"360502198312087132","certificatetype":"0","vehicleColor":"0","vehiclePlate":"赣KL7807"}]}' + ')' ); // 储存卡列表接口原始数据
		var cardInfo = [];// 0卡号 1余额 2车牌
        //alert(JSON.stringify(result));
        
        var isOneStep = false; // 默认正常圈存,如是一步圈存则赋值true
        var isTransfer = true; // 默认直接圈存

        // 链接中没带有参数，则从原始数据中取第一个卡片的信息，原始数据没有卡片，则跳至卡列表页面
		if(!cardNoSelect && !balanceSelect && !vehiclePlateSelect) {
			if (result.length != 0) {
				cardInfo[0] = result[0].cardNo;
				cardInfo[1] = result[0].acctBalance;
				cardInfo[2] = result[0].vehiclePlate;
			}else{
                window.location.href='card/toChangeCardPage?fromPage=transfer';
				// 没绑卡
			}
		}else {
			cardInfo[0] = cardNoSelect;
			cardInfo[1] = balanceSelect;
			cardInfo[2] = vehiclePlateSelect;
		}
        //alert("acctBalance:"+cardInfo[1]);
		// 更换卡片


		// function getAcctBalance(cardNo) {
		// 	console.log('step into getAcctBalance()')
		// 	var data = {
		// 		cardNo: cardNo
		// 	}
		// 	$(".loading").show();
		// 	$.ajax({
		// 		url: 'card/amount',
		// 		type: 'GET',
		// 		dataType: 'json',
		// 		data: data,
		// 		cache: false,
		// 		timeout: 10000,
		// 		success: function(r) {
		//             console.log(r);
		//             $(".loading").hide();

		//             if (r.respCode != "00") {
		//                 alert_LHX({
		//                 	hasBtn: 1,
		//                 	msg: "提示无法获取账号余额，请重试或使用微信支付！"
		//                 });
		//                 $("#transferMoneyBtn").html("--");
		//                 return false;
		//             }
		            
		//             //余额
		// 			$("#transferMoneyBtn").html((cardInfo[1]/100).toFixed(2));

		//         },
		//         error: function(e) {
		//         	$(".loading").hide();
		//         	alert_LHX({
		//             	hasBtn: 1,
		//             	msg: "提示无法获取账号余额，请重试或使用微信支付！"
		//             });		            	        
		//         }
		// 	});
		// }
		// 
		// 
		
		function transferEventHandler() {

			//isTransfer = e.target.id == "debit_btn" ? true : false;
				if(!bleInited){
					errorToast(bleInfo.STAUS_INIT,3);
                    return;
				}
				if(!bleStatus){
					errorToast(bleInfo.STAUS_BLUETOOTH_OFF,3);
                    return;
				}
                var money = $("#transfer_money").val();
                if (money == "00000"){
                    money = 1;
                }else {
                    var regExp = /\D/ig;
                    if (money % 100 != 0 || !money || (+money) == 0 || regExp.test(money)) {
                        alert_LHX({
                            hasBtn: 1,
                            msg: "请输入正确的圈存金额（100的整数倍）"
                        })
                        return false;
                    }

                    if (isTransfer && parseInt(money)*100 > parseInt(cardInfo[1])){
                        alert_LHX({
                            hasBtn: 1,
                            msg: "账户余额不足，请重新输入金额或选择微信支付"
                        })
                        return false;
					}
                    $("#rechange_money").val(+money);
                    money = money * 100;
                }
				if($("#transfer_money").val()){
                	$(".query_find_blue, .mask_layer").removeClass('none');
					ble.getWXDeviceInfos();
                	ble.scanDevice();
				}else{
					alert_LHX({
						hasBtn: 1,
						msg: "请输入圈存金额"
					})
				}
				

				/*
				$(".mask_layer, .query_read_box").removeClass('none');
				//圈存初始化，传入单位：分
				ble.transferInit(money*100);*/
				
			}
		$(function () {
			var opts = {
	            access_token:'${accessToken}',
	            openId:'${openId}',                 //后台返回openid
	            appId:'${wxconfig.appid}',                  //后台返回appid
	            timestamp:'${wxconfig.timestamp}',          //后台返回生成证书时用的时间戳
	            nonceStr:'${wxconfig.noncestr}',            //后台返回生成证书时用的随机串
	            signature:'${wxconfig.signature}',          //后台返回以当前URL地址生成的证书
	        	cardNo: cardInfo[0],
	        };
			if(cardInfo[1] == ""){
                opts.timeout = 3;
			}
	        ble = new Ble();
	        ble.bleInit(opts);

	        if (cardInfo[1] == null || cardInfo[1] == "") {
	        	$("#transferMoneyBtn").html("--");
	        	isOneStep = true; // 一步圈存

	        }else{
				// 绑定圈存按钮事件
				$(".debit_btn").removeClass('disable').on('click',function(){
				    isTransfer = true;
                    transferEventHandler();
				});
				$("#transferMoneyBtn").html((cardInfo[1]/100).toFixed(2));

	        }

	        // 支付按钮
	        $(".goToRecharge").on('click', function(){
                isTransfer =false;
				transferEventHandler();
			});

	        $("#transfer_money").val(""); //清除输入框面缓存
	        //alert("payMoney:"+payMoney);
			try {
				var lastTransferMoney = payMoney || getCookie("lastTransferMoney");
			//	alert("lastTransferMoney"+lastTransferMoney);
				if (lastTransferMoney) {
					//alert("lastTransferMoney"+lastTransferMoney);
					$("#transfer_money").val(lastTransferMoney/100);
					$(".input_holder").addClass('none');
					// $("#transferMoneyBtn").html(lastTransferMoney);
				}
			} catch(e) { }

			// 卡号、车牌写入界面
			$("#transferVpl").html(cardInfo[2]);
			$("#transferCardNo").html("3601 "+cardNumFormat(cardInfo[0]));

			
			$("#transfer_money").on('input', function(e) {
				var val = $(this).val();
				if (val=="") {
					$(".input_holder").removeClass('none');
				}else {
					$(".input_holder").addClass('none');
				}
				// $("#transferMoneyBtn").html(val);
			});

			// // 点击"余額不足?更換微信支付"
			// $(".goToRecharge").click(function(e) {
			// 	window.location.href='payment/toRecharge?createFrom=2&fromPage=transfer&cardNo='+cardInfo[0]+'&acctBalance='+cardInfo[1]+'&vehiclePlate='+cardInfo[2];
			// });


			// 选择蓝牙盒子 
			$(".nextStep").click(function(e) {
				if($(this).hasClass("disable")) return;
				// 开始卡片操作 圈存中
				ble.maskBoxShow("debbting_box");

				var money = $("#transfer_money").val();
				var regExp = /\D/ig;
				if (money == "00000"){
                    money = 1;
                }else {

					if (money%100 != 0 || !money || (+money) == 0 || regExp.test(money)) {
						alert_LHX({
							hasBtn: 1,
							msg: "请输入正确的圈存金额（100的整数倍）"
						})
						return false;
					}

					$("#transfer_money").val(+money);
                    money *= 100;
				}
				
				ble.transferInit(money,isOneStep,isTransfer);
				$(this).addClass("disable");
			});

			//点击弹出框右上角X 关闭遮罩层
			$(".query_close").click(function(e) {
                ble.countover();
				$(".mask_layer, .mask_layer>div").addClass('none');
			});

		})
	</script>
</body>
</html>